from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from myadmin import models
from django.db.models import Q

# 确认订单
def order_confirm(request):
    # 接收传递的数据
    ids = request.GET.get('ids')
    # 将 ids字符串 进行切分
    ids = ids.split(',')
    # 获取购物车数据
    cart = request.session.get('Cart')
    data = {}
    # 循环商品id
    for x in ids:
        # 将传过来的商品从session中获取放入data
        data[x]=cart[x]

    # 分配数据

    # 获取当前用户的所有收获地址 一对多  uid 为当前用户的 id(session里为uid)
    adds = models.Address.objects.filter(uid=request.session['user']['uid'])
    context = {'data': data,'adds':adds}
    return render(request,'home/order/confirm.html',context)

# 添加地址
def address_insert(request):
    # 接收数据
    data = request.GET.dict()
    # 获取用户对象  uid 为 与用户的外键  用户表的 id 等于 当前登录用户的 id
    data['uid'] =models.Users.objects.get(id=request.session['user']['uid'])
    # 判断是否为默认地址
    if data['status'] == '1':
        data['status'] = 1
        # 把其余的 地址改为 非默认  获取用户对象   当前的用户id相等
        obs = models.Address.objects.filter(uid=data['uid'])
        # 循环获得单个对象
        for x in obs:
            # 改变每个对象的 状态
            x.status = 0
            x.save()
    # 执行添加
    ob = models.Address.objects.create(**data)
    return JsonResponse({'error':0,'msg':'地址添加成功'})


# 生成订单
def order_create(request):
    # 获取提交的数据
    # 商品的 id
    ids = request.POST.get('ids')
    # 将字符串id 切分为列表
    ids = ids.split(',')
    # 地址的id
    addid = request.POST.get('addid')
    # 生成订单
    orderdata = {}
    # 外键 与用户关联  用户为当前登录的用户
    orderdata['uid'] = models.Users.objects.get(id=request.session['user']['uid'])
    # 外键 地址
    orderdata['aid'] = models.Address.objects.get(id=addid)
    # 总价  先赋值为0  后面运算
    orderdata['totalprice'] = 0
    # 存库
    ob = models.Order.objects.create(**orderdata)

    # 获取购物车数据
    cart = request.session['Cart']
    totalprice = 0
    # 循环 商品 id
    for x in ids:
        # 创建订单详情对象
        res = models.OrderInfo()
        # 外键 订单id  订单对象
        res.orderid = ob
        # 获取对应商品对象
        goods = models.Goods.objects.get(id = x)
        # 外键 商品 为 对应商品对象
        res.goodsid = goods
        # 商品价格
        res.price = goods.price
        # 商品数量
        res.num = cart[x]['gnum']
        # 存库
        res.save()
        # 删除购物车中对应的商品
        del cart[x]
        # 运算总价
        totalprice += res.price*res.num
        # 扣库存
        goods.num -= res.num
        # 更新商品数据库
        goods.save()
    # 将购物车数据重新存入session
    request.session['Cart'] = cart
    # 更改订单（order）中的 总价
    ob.totalprice = totalprice
    # 更新库
    ob.save()
    return HttpResponse('<script>alert("请支付");location.href="/order/buy/' + str(ob.id) + '/"</script>')

# 支付页面
def order_buy(request,oid):
    # 根据订单号获取 订单信息
    ob = models.Order.objects.get(id=oid)
    # 分配数据
    context = {'order':ob}
    # 返回模板
    return render(request,'home/order/buy.html',context)

# 支付成功
def order_buy_success(request,oid):
    # 获取当前用户的所有订单信息
    ob = models.Order.objects.get(id=oid)
    # 将状态改为已付款
    ob.status = 1
    ob.save()
    return render(request,'home/order/success.html')

# 我的 订单
def myorder(request):
    # 获取当前查询状态
    status = ''
    orderlist = ''
    if request.GET.get('status'):
        status = request.GET.get('status')
    # print(status,type(status))
    # 判断是否有状态
    if status == '':
        # 获取当前用户对象的所有订单 订单与用户关联
        # print('haha')
        orderlist = models.Order.objects.filter(uid=request.session['user']['uid'])
    else:
        # print('esel')
        if status == "0":
            orderlist = models.Order.objects.filter(Q(uid=request.session['user']['uid']) & Q(status=0))
        elif status == "1":
            orderlist = models.Order.objects.filter(Q(uid=request.session['user']['uid']) & Q(status=1))
        elif status == "2":
            orderlist = models.Order.objects.filter(Q(uid=request.session['user']['uid']) & Q(status=2))
    for x in orderlist:
        print(x.id)
   # 分配数据
    context = {'orderlist':orderlist}
    # 返回模板
    return render(request,'home/center/myorder.html',context)


# 订单详情
def myorder_info(request):
    # 接收传来的 id
    id = request.GET.get('oid')
    # 获取订单对象
    obslist = models.Order.objects.filter(id=id)
    # 分配数据
    context = {'obslist': obslist}
    # return render(request, 'admin/order/info.html', context)
    return render(request,'home/center/orderinfo.html',context)